/*
 *  mp3decoder.c
 *  oE6
 *
 *  Created by Tony Million on 12/12/2008.
 *  Copyright 2008 Tony Million. All rights reserved.
 *
 */

#include "mp3decoder.h"

#include "header.h"
#include "sideinfo.h"

int decodeframe(void)
{
	unsigned char	headerbuffer[4];
	unsigned char	sibuffer[64];
	unsigned char	crcbuffer[2];
	unsigned char	adbuffer[2048];
	
	header		theheader;
	sideinfo	thesi;
	
	static int framen = 0;
	
	int success = 0;
	unsigned long bytesread = 0;
	
	if(oEread(headerbuffer, 4)!=4)
		return -1;
	
	bytesread += 4;
	
	if(decodeHeader(headerbuffer, &theheader))
	{
		if(theheader.CRCPresent)
		{
			if(oEread(crcbuffer, 2) != 2)
				return -1;
			bytesread += 2;
		}
		
		if(oEread(sibuffer, theheader.SideInfoSize) != theheader.SideInfoSize)
			return -1;
		bytesread += theheader.SideInfoSize;
		
		if(decodeSideInfo(sibuffer, &thesi, &theheader))
		{
			if(oEread(adbuffer, theheader.AudioDataSize)!=theheader.AudioDataSize)
				return -1;
			
			bytesread += theheader.AudioDataSize;
		}
		else
		{
			printf("Error decoding sideinfo\r\n");
		}
		
		printf("%d\r\n", framen++);
		
		success = 1;
	}

	if(!success)
	{
		oErewind(bytesread-1);
	}
	
	return success;
}